function components = obtain_main_frequency_components(wav_fullname)
% Algorithm that calculates the main frequency components from 
% a wav filename and returns an array with the frequency and the 
% amplitude.
%
% components = [ frequency 1, amplitude 1; frequency 2, amplitude 2; ...]
%

freqs = obtain_wav_frequency_components(wav_fullname);
%components = order_frequency_components(freqs);
components = freqs;
end

function ordered = order_frequency_components(components)
% max amplitude
[val,pos]=max(components(:,2));
max_amp_pos = pos;
max_amp = val;
max_amp_freq = components(pos,1);

significant_pos = -1;

for i=1:size(components,1)
    f = components(i,1);
    rel_amplitude = components(i,2)/max_amp;
    if ( f < max_amp_freq && rel_amplitude > 0.5)
        significant_pos = i;
        break;
    end
end    

%if exists a lower freq significant peak
if (significant_pos > 0) 
    ordered = [components(significant_pos,1) components(significant_pos,2) ];
    ordered = [ordered; components(max_amp_pos,1) components(max_amp_pos,2) ];
else
    ordered = [components(max_amp_pos,1) components(max_amp_pos,2) ];
end

%append the remaining peaks
for i=1:size(components,1)
    if (i~= significant_pos) 
        if ( i~= max_amp_pos) 
            ordered = [ordered; components(i,1) components(i,2) ];
        end
    end
end    




% % order by freq ascending
% [val,pos]=min(components(:,1));
% ordered = [components(pos,1) components(pos,2)/max_amp ];
% components(pos,1) = 4000;
% for i=2:size(components,1)
% %    disp(['>>Peak:' num2str(ordered(i,2)) ' ' num2str(ordered(i,1)) ' Hz']);
%     [val,pos]=min(components(:,1));
%     ordered = [ordered; components(pos,1) components(pos,2)/max_amp ];
%     components(pos,1) = 4000;
% end

% % order by freq descending
% [val,pos]=max(components(:,1));
% ordered = [components(pos,1) components(pos,2)/max_amp ];
% components(pos,1) = 0;
% for i=2:size(components,1)
% %    disp(['>>Peak:' num2str(ordered(i,2)) ' ' num2str(ordered(i,1)) ' Hz']);
%     [val,pos]=max(components(:,1));
%     ordered = [ordered; components(pos,1) components(pos,2)/max_amp ];
%     components(pos,1) = 0;
% end

end
